package com.meiyuetao.myt.crawl.web.action;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.pagination.GroupPropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter.MatchType;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.web.view.OperationResult;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.rest.HttpHeaders;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import com.google.common.collect.Lists;
import com.meiyuetao.myt.core.service.SolrService;
import com.meiyuetao.myt.core.web.MytBaseController;
import com.meiyuetao.myt.crawl.entity.ParseCommodity;
import com.meiyuetao.myt.crawl.entity.ParsePropTrack;
import com.meiyuetao.myt.crawl.service.ParseCommodityService;
import com.meiyuetao.myt.crawl.service.ParsePropTrackService;
import com.meiyuetao.myt.md.entity.Brand;
import com.meiyuetao.myt.md.entity.Commodity;
import com.meiyuetao.myt.md.entity.Commodity.CommodityAuditStatusEnum;
import com.meiyuetao.myt.md.entity.CommodityPic;
import com.meiyuetao.myt.md.entity.CommodityPrice;
import com.meiyuetao.myt.md.service.BrandService;
import com.meiyuetao.myt.md.service.CommodityPriceService;
import com.meiyuetao.myt.md.service.CommodityService;
import com.meiyuetao.myt.partner.entity.Partner;
import com.meiyuetao.myt.partner.service.PartnerService;

@MetaData("ParseCommodity")
public class ParseCommodityController extends MytBaseController<ParseCommodity, Long> {

    @Autowired
    private ParseCommodityService parseCommodityService;
    @Autowired
    private ParsePropTrackService parsePropTrackService;
    @Autowired
    private CommodityService commodityService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private SolrService solrService;
    @Autowired
    private PartnerService partnerService;
    @Autowired
    private CommodityPriceService commodityPriceService;

    @Override
    protected BaseService<ParseCommodity, Long> getEntityService() {
        return parseCommodityService;
    }

    @Override
    protected void checkEntityAclPermission(ParseCommodity entity) {
        // TODO Add acl check code logic
    }

    @Override
    @MetaData("保存")
    public HttpHeaders doSave() {
        return super.doSave();
    }

    @Override
    @MetaData("删除")
    public HttpHeaders doDelete() {
        return super.doDelete();
    }

    @Override
    @MetaData("查询")
    public HttpHeaders findByPage() {
        return super.findByPage();
    }

    @MetaData(value = "关联属性")
    public HttpHeaders getParsePropTracks() {
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "baseUrl", bindingEntity.getBaseUrl()));
        List<ParsePropTrack> parsePropTracks = parsePropTrackService.findByFilters(groupPropertyFilter);
        setModel(buildPageResultFromList(parsePropTracks));
        return buildDefaultHttpHeaders();
    }

    public HttpHeaders doAIInit() {
        List<ParseCommodity> parseCommodities = null;
        Long[] ids = this.getSelectSids();
        if (ids != null && ids.length > 0) {
            parseCommodities = parseCommodityService.findAll(ids);
        } else {
            GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
            parseCommodities = parseCommodityService.findByFilters(groupPropertyFilter);
        }

        Map<Brand, Set<String>> brandTokensMap = brandService.getAllBrandTokens();

        for (ParseCommodity parseCommodity : parseCommodities) {
            solrService.calcParseCommodity(parseCommodity, brandTokensMap);
        }
        setModel(OperationResult.buildSuccessResult("完成自动初始化" + parseCommodities.size() + "条数据"));
        return buildDefaultHttpHeaders();
    }

    public HttpHeaders doImport() {
        List<ParseCommodity> parseCommodities = null;
        Long[] ids = this.getSelectSids();
        if (ids != null && ids.length > 0) {
            parseCommodities = parseCommodityService.findAll(ids);
        } else {
            GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
            parseCommodities = parseCommodityService.findByFilters(groupPropertyFilter);
        }
        // Partner partner = partnerService.findByProperty("code", "PNRPSET");

        Partner partner = this.getLogonPartner();
        for (ParseCommodity parseCommodity : parseCommodities) {
            Commodity commodity = commodityService.findByProperty("sourceUrl", parseCommodity.getBaseUrl());
            if (commodity == null) {
                commodity = new Commodity();
                commodity.setCanSaleCount(new BigDecimal(200));
                String sku = RandomStringUtils.randomNumeric(8);
                while (commodityService.findBySku(sku) != null) {
                    sku = RandomStringUtils.randomNumeric(8);
                }
                commodity.setSku(sku);
                commodity.setDailyUserCanBuy(20);
                commodity.setPartner(partner);
                commodity.setSource(parseCommodity.getSourceType());
                commodity.setSourceUid(parseCommodity.getSourceCode());
                commodity.setSourceUrl(parseCommodity.getBaseUrl());
                commodity.setRecommendRank(Commodity.RANK_API_TBD);
                commodity.setPrice(parseCommodity.getTargetSalePrice() != null ? parseCommodity.getTargetSalePrice() : parseCommodity.getSalePrice());
                if (commodity.getPrice() != null) {
                    commodity.setMarketPrice(commodity.getPrice().multiply(new BigDecimal(1.3)).setScale(1, BigDecimal.ROUND_HALF_EVEN));
                }

                Assert.isTrue(commodity.getPrice() != null && commodity.getPrice().compareTo(BigDecimal.ZERO) > 0, "价格不能为空");

                commodity.setCommodityAuditStatus(CommodityAuditStatusEnum.A30PASSED);
                commodity.setAuditDate(new Date());
                commodity.setAuditExplain("第三方导入创建审核商品");
            }

            commodity.setTitle(StringUtils.isNotBlank(parseCommodity.getTargetTitle()) ? parseCommodity.getTargetTitle() : parseCommodity.getTitle());
            commodity.setSpecification(parseCommodity.getDescription());
            if (parseCommodity.getTargetBrand() != null) {
                commodity.setBrand(parseCommodity.getTargetBrand());
            }
            if (parseCommodity.getTargetCategory() != null) {
                commodity.setCategory(parseCommodity.getTargetCategory());
            }
            if (CollectionUtils.isEmpty(commodity.getCommodityPics())) {
                GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
                groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "baseUrl", parseCommodity.getBaseUrl()));
                groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "propGroup", "commodity.window.imgs"));
                List<ParsePropTrack> parsePropTracks = parsePropTrackService.findByFilters(groupPropertyFilter);
                // 如果没有橱窗图，则跳过
                if (CollectionUtils.isNotEmpty(parsePropTracks)) {
                    commodity.setSmallPic(parseImgMD5Code(parsePropTracks.get(0).getPropValue()));
                    List<CommodityPic> commodityPics = Lists.newArrayList();
                    int idx = 1000;
                    for (ParsePropTrack parsePropTrack : parsePropTracks) {
                        CommodityPic commodityPic = new CommodityPic();
                        commodityPic.setCommodity(commodity);
                        commodityPic.setPicIndex(idx);
                        commodityPic.setBigPicUrl(parseImgMD5Code(parsePropTrack.getPropValue()));
                        idx = idx - 100;
                        commodityPics.add(commodityPic);
                    }
                    commodity.setCommodityPics(commodityPics);
                    commodity.setPicCount(commodityPics.size());
                }

            }

            if (CollectionUtils.isEmpty(commodity.getCommodityPrices())) {
                BigDecimal lowestPrice = commodityPriceService.calcLowestPrice(commodity);
                if (lowestPrice != null) {
                    DateTime startDate = new DateTime();
                    DateTime endDate = startDate.plusMonths(3);
                    List<CommodityPrice> commodityPriceDrafts = commodityPriceService.calcCommodityPricesByGrade(startDate, endDate, commodity.getPrice(), lowestPrice, 11);
                    for (CommodityPrice commodityPrice : commodityPriceDrafts) {
                        commodityPrice.setCommodity(commodity);

                    }
                    commodity.setCommodityPrices(commodityPriceDrafts);
                }
            }

            commodityService.save(commodity);
            parseCommodity.setLastImportTime(new Date());
            parseCommodityService.save(parseCommodity);
        }

        setModel(OperationResult.buildSuccessResult("完成自动初始化" + parseCommodities.size() + "条数据"));
        return buildDefaultHttpHeaders();
    }

    private static Pattern IMG_MD5_PATTERN = Pattern.compile("http://img.iyoubox.com/GetFileByCode.aspx\\?code=(.*)");

    private String parseImgMD5Code(String url) {
        String code = null;
        Matcher matcher = IMG_MD5_PATTERN.matcher(url);
        if (matcher.find()) {
            code = matcher.group(1);
        }
        Assert.notNull(code);
        return code;
    }
}